package com.ardf.service.impl;

import com.ardf.common.EntityConstants;
import com.ardf.entity.Group;
import com.ardf.entity.Project;
import com.ardf.entity.Rule;
import com.ardf.entity.dto.GroupIdDto;
import com.ardf.mapper.GroupMapper;
import com.ardf.mapper.ProjectMapper;
import com.ardf.service.IGroupService;
import com.ardf.service.IRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ShiYunHao
 * @since 2025-01-06
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group> implements IGroupService {

    private final ProjectMapper projectMapper;
    private final GroupMapper groupMapper;
    private final IRuleService ruleService;

    public GroupServiceImpl(ProjectMapper projectMapper, IRuleService ruleService, GroupMapper groupMapper) {
        this.ruleService = ruleService;
        this.projectMapper = projectMapper;
        this.groupMapper = groupMapper;
    }

    @Override
    @Transactional
    public void saveAll(List<Group> groups) {
        groupMapper.insert(groups);
        List<Group> groupList = groupMapper.selectList(new LambdaQueryWrapper<Group>()
                .in(Group::getName, groups.stream().map(Group::getName).toList())
                .eq(Group::getCompetitionId, groups.get(0).getCompetitionId()));

        
        List<Project> projectList = projectMapper.selectList(new LambdaQueryWrapper<Project>()
                .eq(Project::getCompetitionId, groups.get(0).getCompetitionId()));

        if (!projectList.isEmpty()) {
            List<Rule> rules = groupList.stream().map(group -> projectList.stream()
                    .filter(project -> !"公开组".equals(group.getName()) ||
                            !EntityConstants.PROJECT_CATEGORY_RELAY.equals(project.getCategory()))
                    .map(project -> {
                        Rule rule = new Rule();
                        rule.setGroupId(group.getId());
                        rule.setProjectId(project.getId());
                        return rule;
                    }).toList())
                    .flatMap(List::stream)
                    .toList();
            ruleService.addByBatch(rules);
        }
    }

    @Override
    @Transactional
    public void deleteAll(List<Long> ids) {
        Long competitionId = groupMapper.selectById(ids.get(0)).getCompetitionId();
        long count = projectMapper.selectCount(new LambdaQueryWrapper<Project>()
                .eq(Project::getCompetitionId, competitionId));
        if (count != 0) {
            List<Long> ruleIds = ruleService.listObjs(new LambdaQueryWrapper<Rule>().select(Rule::getId)
                    .in(Rule::getGroupId, ids));
            if (ruleIds != null && !ruleIds.isEmpty()) {
                ruleService.deleteByBatch(ruleIds);
            }
        }
        groupMapper.deleteByIds(ids);
    }

    @Override
    @Transactional
    public void deleteOne(Long id) {
        Long competitionId = groupMapper.selectById(id).getCompetitionId();
        long count = projectMapper.selectCount(new LambdaQueryWrapper<Project>()
                .eq(Project::getCompetitionId, competitionId));
        if (count != 0) {
            List<Long> ruleIds = ruleService.listObjs(new LambdaQueryWrapper<Rule>().select(Rule::getId)
                    .eq(Rule::getGroupId, id));
            if (ruleIds != null && !ruleIds.isEmpty()) {
                ruleService.deleteByBatch(ruleIds);
            }
        }
        groupMapper.deleteById(id);
    }

    @Override
    public GroupIdDto getIdByAge(int age, String gender, Long competitionId) {
        GroupIdDto groupIdDto = new GroupIdDto();
        Group group = null;
        String groupName = null;
        //得到组别名称
        groupName=BackGroupName(age,gender);

        group = groupMapper.selectOne(new LambdaQueryWrapper<Group>()
                .eq(Group::getName, groupName)
                .eq(Group::getCompetitionId, competitionId));
        if (group != null) {
            groupIdDto.setGroupId(group.getId());
        } else {
            groupIdDto.setGroupId(null);
        }
        return groupIdDto;
    }

    @Override
    public Group getGroupByAge(int age, String gender, Long competitionId) {
        Group group = null;
        String groupName = null;

        //得到组别名称
        groupName=BackGroupName(age,gender);

        group = groupMapper.selectOne(new LambdaQueryWrapper<Group>()
                .eq(Group::getName, groupName)
                .eq(Group::getCompetitionId, competitionId));
        return Objects.requireNonNullElseGet(group, Group::new);
    }

    /**
     * author:容伟洪
     * time:2025-3-23
     * description：默认情况：根据组别和性别获取组别名称
     */
    public String BackGroupName(int age,String sex){
        String groupName = "";
        if(sex.equals("女")|| sex=="女"){
            if (age <= 10) {
                groupName = "W10";
            } else if (age <= 12) {
                groupName = "W12";
            } else if (age <= 14) {
                groupName = "W14";
            } else if (age <= 16) {
                groupName = "W16";
            } else if (age <= 19) {
                groupName = "W19";
            } else if (age <= 22) {
                groupName = "W22";
            } else if (age <= 35) {
                groupName = "W35";
            } else if (age <= 45) {
                groupName = "W45";
            } else if (age <= 55) {
                groupName = "W55";
            } else {
                groupName = "W65";
            }
        }
        if(sex.equals("男")|| sex=="男"){
            if (age <= 10) {
                groupName = "M10";
            } else if (age <= 12) {
                groupName = "M12";
            } else if (age <= 14) {
                groupName = "M14";
            } else if (age <= 16) {
                groupName = "M16";
            } else if (age <= 19) {
                groupName = "M19";
            } else if (age <= 22) {
                groupName = "M22";
            } else if (age <= 35) {
                groupName = "M35";
            } else if (age <= 45) {
                groupName = "M45";
            } else if (age <= 55) {
                groupName = "M55";
            } else {
                groupName = "M65";
            }
        }
        return groupName;
    }
}
